package com.kx.center.controller;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kx.center.auth.Authentication;
import com.kx.center.common.Constant;
import com.kx.center.common.CustomHashMap;
import com.kx.center.entity.Account;
import com.kx.center.entity.Address;
import com.kx.center.entity.Food;
import com.kx.center.entity.MsgNotice;
import com.kx.center.entity.StoreAppAccount;
import com.kx.center.entity.StoreInfo;
import com.kx.center.entity.query.QueryFoodCategory;
import com.kx.center.entity.query.QueryResult;
import com.kx.center.entity.shop.ShopOrder;
import com.kx.center.entity.shop.ShopOrderGoods;
import com.kx.center.entity.shop.ShopOrderPay;
import com.kx.center.enumerate.MessageCode;
import com.kx.center.exception.EmptyTokenException;
import com.kx.center.exception.IllegalTokenException;
import com.kx.center.service.FoodService;
import com.kx.center.service.MsgNoticeService;
import com.kx.center.service.SendEmailService;
import com.kx.center.service.ShopOrderService;
import com.kx.center.service.StoreAppAccountService;
import com.kx.center.service.StoreManagerService;
import com.kx.center.util.DateUtil;
import com.kx.center.util.JSONParser;
import com.kx.center.util.Response;
import com.kx.center.util.WXUtil;
import com.kx.center.util.ZFBUtil;

@Controller
@RequestMapping("/shopOrder")
public class ShopOrderController extends CommonController {

	@Autowired
	private ShopOrderService shopOrderService;
	@Autowired
	private StoreAppAccountService storeAppAccountService;
	@Autowired
	private MsgNoticeService msgNoticeService;
	@Autowired
	private FoodService foodService;
	@Autowired
	private SendEmailService sendEmailService;
	@Autowired
	private StoreManagerService storeManagerService;

	// app端订货单列表
	@RequestMapping(value = "list", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String shop_order_list_app(HttpServletRequest request)
			throws EmptyTokenException, IllegalTokenException {

		StoreAppAccount storeAppAccount = this.getStoreAppAccount(request);
		if (storeAppAccount == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		Integer page, pageSize, status;
		QueryFoodCategory queryFoodCategory = new QueryFoodCategory();
		List<Integer> orderStatus = new ArrayList<Integer>();

		String sortBy = request.getParameter("sortBy");
		String sortMethod = request.getParameter("sortMethod");

		page = NumberUtils.toInt(request.getParameter("page_num"));
		pageSize = NumberUtils.toInt(request.getParameter("page_size"));
		status = NumberUtils.toInt(request.getParameter("status"));

		if (StringUtils.isBlank(sortBy))
			sortBy = "create_time";

		if (StringUtils.isBlank(sortMethod))
			sortMethod = "desc";

		queryFoodCategory.setSortBy(sortBy);
		queryFoodCategory.setSortMethod(sortMethod);
		queryFoodCategory.setPage(page);
		queryFoodCategory.setPageSize(pageSize);
		queryFoodCategory.setStoreId(storeAppAccount.getStoreInfoId());

		if (status == 1) {
			orderStatus.add(-1);
			orderStatus.add(7);
			orderStatus.add(3);
		} else if (status == 2) {
			orderStatus.add(1);
		} else if (status == 3) {
			orderStatus.add(2);
			orderStatus.add(8);
			orderStatus.add(5);
		} else if (status == 4) {
			orderStatus.add(4);
			orderStatus.add(6);
		} else {
			return Response.error(MessageCode.NO_DATA);
		}

		queryFoodCategory.setOrderStatus(orderStatus);

		QueryResult result = shopOrderService.queryShopOrder(queryFoodCategory);

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("page", result.getPage());
		map.put("pageSize", result.getPageSize());
		map.put("totalRecord", result.getTotalRecord());
		map.put("data", result.getData());

		return Response.success(map);

	}

	// 后台订货单列表
	@RequestMapping(value = "list/web", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String shop_order_list_web(HttpServletRequest request)
			throws Exception {

		Account account = this.getCommonUserAccount(request);
		if (account == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		Integer page, pageSize, status;
		Date from = null, to = null;
		QueryFoodCategory queryFoodCategory = new QueryFoodCategory();

		String sortBy = request.getParameter("sortBy");
		String sortMethod = request.getParameter("sortMethod");
		String store_id = request.getParameter("store");
		String fromStr = request.getParameter("from");
		String toStr = request.getParameter("to");

		page = NumberUtils.toInt(request.getParameter("page_num"));
		pageSize = NumberUtils.toInt(request.getParameter("page_size"));
		status = NumberUtils.toInt(request.getParameter("status"));

		if (DateUtil.isDate(fromStr))
			from = DateUtils.parseDate(fromStr, "yyyy-MM-dd");

		if (DateUtil.isDate(toStr))
			to = DateUtils
					.parseDate(toStr + " 23:59:59", "yyyy-MM-dd HH:mm:ss");

		if (StringUtils.isBlank(sortBy))
			sortBy = "create_time";

		if (StringUtils.isBlank(sortMethod))
			sortMethod = "desc";

		queryFoodCategory.setFrom(from);
		queryFoodCategory.setTo(to);
		queryFoodCategory.setSortBy(sortBy);
		queryFoodCategory.setSortMethod(sortMethod);
		queryFoodCategory.setPage(page);
		queryFoodCategory.setPageSize(pageSize);
		queryFoodCategory.setStatus(status);
		queryFoodCategory.setCompanyId(account.getCompanyId());
		queryFoodCategory.setStoreId(Integer.parseInt(store_id));

		QueryResult result = shopOrderService.queryShopOrder(queryFoodCategory);

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("page", result.getPage());
		map.put("pageSize", result.getPageSize());
		map.put("totalRecord", result.getTotalRecord());
		map.put("data", result.getData());

		return Response.success(map);
	}

	// 订货详情(共用)
	@RequestMapping(value = "detail/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String shop_order_detail(HttpServletRequest request,
			@PathVariable("id") Integer id) {

		if (id != null && id > 0) {
			List<ShopOrderGoods> details = shopOrderService
					.findShopOrderGoodsById(id);

			ShopOrder shopOrder = shopOrderService.findShopOrderById(id);
			//查询对应的收货地址
			Address address = shopOrderService.findShopOrderAddress(id);

			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("data", details);
			map.put("address", address);
			map.put("orderStatus", shopOrder.getOrderStatus());
			map.put("goodsAmount", shopOrder.getGoodsAmount());
			
			return Response.success(shopOrder.getReason(), map);
		} else {
			return Response.error(MessageCode.NO_DATA);
		}
	}

	// app端创建订货单接口
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "create", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String shop_order_create(HttpServletRequest request)
			throws EmptyTokenException, IllegalTokenException {

		StoreAppAccount storeAppAccount = this.getStoreAppAccount(request);
		if (storeAppAccount == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		StoreInfo storeInfo = storeManagerService
				.findStoreInfoById(storeAppAccount.getStoreInfoId());
		if (storeInfo == null) {
			return Response.error(MessageCode.STORE_ID_WRONG);
		}

		String json = request.getParameter("data");

		if (StringUtils.isBlank(json)) {
			return Response.error(MessageCode.JSON_WRONG);
		}

		ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
		try {
			data = (ArrayList<HashMap<String, Object>>) JSONParser.parse(json,
					new ArrayList<HashMap<String, Object>>().getClass());
		} catch (Exception e) {
			e.printStackTrace();
			return Response.error(MessageCode.JSON_WRONG);
		}

		for (HashMap<String, Object> map : data) {
			CustomHashMap<String, Object> item = CustomHashMap.convert(map);
			if (item.getInteger("num") == 0) {
				return Response.error(MessageCode.PARAMETER_WRONG);
			}
			Food food = foodService.findFoodById(item.getInteger("id"));
			if (food == null || food.getStatus() != 1) {
				return Response.error(MessageCode.FOOD_ID_NOT);
			}
		}
		Integer addressId = NumberUtils.toInt(data.get(0).get("addressId").toString());
		if(addressId <= 0){
			//收货地址不存在
			return Response.error("收货地址为空");
		}
		
		String orderNum = shopOrderService.saveShopOrder(storeAppAccount,
				storeInfo, data);

		try {
			String template = "auditTemplate";
			String now = DateUtil.formatDateTime(new Date());
			List<String> email = shopOrderService.mailRecipient(storeInfo
					.getCompanyId());
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("storeName", storeInfo.getStoreName());
			model.put("url", Constant.WEB_MANAGER_URL);
			model.put("orderNum", orderNum);
			model.put("year", now.substring(0, 4));
			model.put("month", now.substring(5, 7));
			model.put("day", now.substring(8, 10));
			model.put("time", now.substring(11, 19));
			sendEmailService.sendEmailFromTemplate(template, email, model);
		} catch (Exception e) {
			return Response.success("订货单提交成功，邮件发送失败!");
		}

		return Response.success("订货单提交成功!");
	}

	// app端取消订单接口
	@RequestMapping(value = "cancel", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String shop_order_cancel(HttpServletRequest request)
			throws EmptyTokenException, IllegalTokenException {

		StoreAppAccount storeAppAccount = this.getStoreAppAccount(request);
		if (storeAppAccount == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		String id = request.getParameter("id");

		try {
			Integer.parseInt(id);
		} catch (Exception e) {
			return Response.error(MessageCode.STOCKIN_ID_WRONG);
		}

		ShopOrder shopOrder = shopOrderService.findShopOrderById(Integer
				.parseInt(id));
		if (shopOrder == null) {
			return Response.error(MessageCode.STOCKIN_ID_WRONG);
		} else if (shopOrder.getOrderStatus() != 1) {
			return Response.error(MessageCode.REQUEST_ERROR);
		} else {
			shopOrder.setId(Integer.parseInt(id));
			shopOrder.setOrderStatus(-1);
			shopOrderService.cancelShopOrder(shopOrder);
		}

		return Response.success("订货单已取消!");

	}

	// 后台确认订单接口
	@RequestMapping(value = "confirm", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String shop_order_confirm(HttpServletRequest request) {

		Account account = this.getCommonUserAccount(request);
		if (account == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		String id = request.getParameter("id");

		if (StringUtils.isBlank(id)) {
			return Response.error(MessageCode.PARAMETER_WRONG);
		}

		ShopOrder shopOrder = shopOrderService.findShopOrderById(Integer
				.parseInt(id));
		if (shopOrder == null) {
			return Response.error(MessageCode.ORDER_ID_WRONG);
		} else {
			if (shopOrder.getOrderStatus() != 1) {
				return Response.error(MessageCode.OPERATOR_FAIL);
			}
		}

		shopOrder.setId(Integer.parseInt(id));
		shopOrder.setOrderStatus(2);
		shopOrder.setOperatorId(account.getOperatorId());
		shopOrderService.confirmShopOrder(shopOrder);

		ArrayList<HashMap<String, Object>> data = shopOrderService
				.pushClientMessage(shopOrder);
		MsgNotice msgNotice = new MsgNotice();
		msgNotice.setTitle("您于"
				+ DateUtil.formatDateTime(shopOrder.getCreateTime())
				+ "提交的订单审核已发货，点击了解详情!");
		msgNotice.setContent("您提交的订单" + shopOrder.getOrderNum()
				+ "已发货，请收到药品后及时确认!");
		msgNotice.setOperatorId(account.getOperatorId());
		msgNotice.setCompanyId(account.getCompanyId());
		msgNotice.setOrderId(Integer.parseInt(id));
		msgNotice.setOrderStatus(2);
		msgNoticeService.sendNoticeMsg(msgNotice, data);

		return Response.success("发货成功");
	}

	// 后台取消订单接口
	@RequestMapping(value = "reject", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String shop_order_reject(HttpServletRequest request)
			throws Exception {

		Account account = this.getCommonUserAccount(request);
		if (account == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		String id = request.getParameter("id");
		String reason = StringUtils.trimToEmpty(request.getParameter("reason"));

		if (StringUtils.isBlank(reason)) {
			return Response.error(MessageCode.REASON_IS_NOT_NULL);
		}

		if (StringUtils.isBlank(id)) {
			return Response.error(MessageCode.PARAMETER_WRONG);
		}

		ShopOrder shopOrder = shopOrderService.findShopOrderById(Integer
				.parseInt(id));
		if (shopOrder == null || shopOrder.getOrderStatus() != 1) {
			return Response.error(MessageCode.OPERATOR_FAIL);
		}

		shopOrder.setId(Integer.parseInt(id));
		shopOrder.setOrderStatus(3);
		shopOrder.setOperatorId(account.getOperatorId());
		shopOrder.setReason(reason);
		shopOrderService.rejectShopOrder(shopOrder);

		ArrayList<HashMap<String, Object>> data = shopOrderService
				.pushClientMessage(shopOrder);
		MsgNotice msgNotice = new MsgNotice();
		msgNotice.setTitle("您于"
				+ DateUtil.formatDateTime(shopOrder.getCreateTime())
				+ "提交的订单已取消，点击了解详情!");
		msgNotice.setContent(reason);
		msgNotice.setOperatorId(account.getOperatorId());
		msgNotice.setCompanyId(account.getCompanyId());
		msgNotice.setOrderId(Integer.parseInt(id));
		msgNotice.setOrderStatus(3);
		msgNoticeService.sendNoticeMsg(msgNotice, data);

		return Response.success("取消订货单成功");
	}

	// web端发货接口
	@RequestMapping(value = "deliver", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String shop_order_deliver(HttpServletRequest request) {

		Account account = this.getCommonUserAccount(request);
		if (account == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		String id = request.getParameter("id");

		if (StringUtils.isBlank(id)) {
			return Response.error(MessageCode.PARAMETER_WRONG);
		}

		ShopOrder shopOrder = shopOrderService.findShopOrderById(Integer
				.parseInt(id));
		if (shopOrder == null) {
			return Response.error(MessageCode.ORDER_ID_WRONG);
		} else {
			if (shopOrder.getOrderStatus() != 4) {
				return Response.error(MessageCode.OPERATOR_FAIL);
			}
		}

		shopOrder.setId(Integer.parseInt(id));
		shopOrder.setOrderStatus(6);
		shopOrder.setOperatorId(account.getOperatorId());
		shopOrderService.deliverShopOrder(shopOrder);

		ArrayList<HashMap<String, Object>> data = shopOrderService
				.pushClientMessage(shopOrder);
		MsgNotice msgNotice = new MsgNotice();
		msgNotice.setTitle("您于"
				+ DateUtil.formatDateTime(shopOrder.getCreateTime())
				+ "提交的订单已发货，点击了解详情!");
		msgNotice.setContent("您提交的订单" + shopOrder.getOrderNum() + "已发货，请耐心等待!");
		msgNotice.setOperatorId(account.getOperatorId());
		msgNotice.setCompanyId(account.getCompanyId());
		msgNotice.setOrderId(Integer.parseInt(id));
		msgNotice.setOrderStatus(6);
		msgNoticeService.sendNoticeMsg(msgNotice, data);

		return Response.success("订货单发货完成!");

	}

	// app提交付款接口
	@RequestMapping(value = "payment", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String shop_order_payment(HttpServletRequest request)
			throws Exception {

		StoreAppAccount storeAppAccount = this.getStoreAppAccount(request);
		if (storeAppAccount == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		String id = request.getParameter("id");
		String payment_channel = request.getParameter("payment_channel");

		try {
			Integer.parseInt(id);
			Integer.parseInt(payment_channel);
		} catch (Exception e) {
			return Response.error(MessageCode.PARAMETER_WRONG);
		}

		ShopOrder shopOrder = shopOrderService.findShopOrderById(Integer
				.parseInt(id));
		if (shopOrder == null) {
			return Response.error(MessageCode.ORDER_ID_WRONG);
		} else if (shopOrder.getOrderStatus() != 2
				&& shopOrder.getOrderStatus() != 5) {
			return Response.error(MessageCode.REQUEST_ERROR);
		}

		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("data", shopOrderService.saveShopOrderPay(request,
				Integer.parseInt(id), Integer.parseInt(payment_channel)));
		map.put("orderStatus", shopOrder.getOrderStatus());
		return Response.success(map);

	}

	// web确认是否已收款
	@RequestMapping(value = "payment/offline", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String shop_order_payment_offline(HttpServletRequest request)
			throws EmptyTokenException, IllegalTokenException {

		Account account = this.getCommonUserAccount(request);
		if (account == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		String id = request.getParameter("id");

		try {
			Integer.parseInt(id);
		} catch (Exception e) {
			return Response.error(MessageCode.ORDER_ID_WRONG);
		}

		ShopOrder shopOrder = shopOrderService.findShopOrderById(Integer
				.parseInt(id));
		if (shopOrder == null) {
			return Response.error(MessageCode.ORDER_ID_WRONG);
		} else if (shopOrder.getOrderStatus() != 2) {
			return Response.error(MessageCode.REQUEST_ERROR);
		}

		shopOrder.setId(Integer.parseInt(id));
		shopOrder.setOrderStatus(4);
		shopOrder.setOperatorId(account.getOperatorId());
		shopOrderService.paymentShopOrder(shopOrder);

		ArrayList<HashMap<String, Object>> data = shopOrderService
				.pushClientMessage(shopOrder);
		MsgNotice msgNotice = new MsgNotice();
		msgNotice.setTitle("您于"
				+ DateUtil.formatDateTime(shopOrder.getCreateTime())
				+ "提交的订单已确认收款，点击了解详情!");
		msgNotice.setContent("您提交的订单" + shopOrder.getOrderNum() + "已确认收款!");
		msgNotice.setOperatorId(account.getOperatorId());
		msgNotice.setCompanyId(account.getCompanyId());
		msgNotice.setOrderId(Integer.parseInt(id));
		msgNotice.setOrderStatus(4);
		msgNoticeService.sendNoticeMsg(msgNotice, data);

		return Response.success("订单状态更改成功!");
	}

	// app更改付款状态接口
	@RequestMapping(value = "payment/confirmation", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String shop_order_payment_confirmation(HttpServletRequest request)
			throws EmptyTokenException, IllegalTokenException {

		StoreAppAccount storeAppAccount = this.getStoreAppAccount(request);
		if (storeAppAccount == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		String id = request.getParameter("id");

		try {
			Integer.parseInt(id);
		} catch (Exception e) {
			return Response.error(MessageCode.ORDER_ID_WRONG);
		}

		ShopOrder shopOrder = shopOrderService.findShopOrderById(Integer
				.parseInt(id));
		if (shopOrder == null) {
			return Response.error(MessageCode.ORDER_ID_WRONG);
		} else if (shopOrder.getOrderStatus() != 2) {
			return Response.error(MessageCode.REQUEST_ERROR);
		}

		shopOrder.setId(Integer.parseInt(id));
		shopOrder.setOrderStatus(8);
		shopOrderService.paymentShopOrder(shopOrder);

		return Response.success("订单状态更改成功!");

	}

	// 微支付推送付款结果
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "payment/wzfPush", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String shop_order_payment_push_wzf(HttpServletRequest request)
			throws Exception {

		java.io.BufferedInputStream bis = new java.io.BufferedInputStream(
				request.getInputStream());

		byte read[] = new byte[1024 * 1024];
		String loc = "";

		try {
			while ((bis.read(read, 0, 1 * 1)) != -1) {

				loc += (new String(read, 0, 1 * 1));
			}
		} catch (Exception e) {

		} finally {
			bis.close();
		}
		
		HashMap<String, Object> data = WXUtil.xmlToMap(loc);
		CustomHashMap<String, Object> item = CustomHashMap.convert(data);
		
		if(WXUtil.checkSign(data)){
			if(item.getString("result_code").equals("SUCCESS")){
				String id = item.getString("attach");
				ShopOrder shopOrder = shopOrderService.findShopOrderById(Integer.parseInt(id));
				if(shopOrder.getOrderStatus() == 4){
					//目前不处理业务逻辑
				}else{
					
					shopOrderService.updateOrderAndPayStatus(data, 3);
					try {
						String template = "paymentTemplate";
						List<String> email = shopOrderService
								.mailRecipient(shopOrder.getCompanyId());
						Map<String, Object> model = new HashMap<String, Object>();
						model.put("storeName", shopOrder.getShopName());
						model.put("orderNum", shopOrder.getOrderNum());
						model.put("url", Constant.WEB_MANAGER_URL);
						model.put("year",
								DateUtil.formatDateTime(shopOrder.getCreateTime())
										.substring(0, 4));
						model.put("month",
								DateUtil.formatDateTime(shopOrder.getCreateTime())
										.substring(5, 7));
						model.put("day",
								DateUtil.formatDateTime(shopOrder.getCreateTime())
										.substring(8, 10));
						model.put("time",
								DateUtil.formatDateTime(shopOrder.getCreateTime())
										.substring(11, 19));
						sendEmailService.sendEmailFromTemplate(template, email,
								model);
					} catch (Exception e) {
						return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
					}
				}
			}
			
			return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
		}else{
			
			return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
		}
	}

	// 支付宝推送付款结果
	@RequestMapping(value = "payment/zfbPush", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String shop_order_payment_push_zfb(HttpServletRequest request)
			throws Exception {
		
		HashMap<String, Object> data = new HashMap<String, Object>();
		HashMap<String, String> zfb = new LinkedHashMap<String, String>();
		
		Enumeration<?> pNames = request.getParameterNames();
		while (pNames.hasMoreElements()) {
			String name = (String) pNames.nextElement();
			String value = request.getParameter(name);
			data.put(name, value);
			zfb.put(name, value);
		}

		String trade_status = new String(request.getParameter("trade_status")
				.getBytes("ISO-8859-1"), "UTF-8");
		String out_trade_no = new String(request.getParameter("out_trade_no")
				.getBytes("ISO-8859-1"), "UTF-8");

		if (ZFBUtil.verify(zfb)) {

			if (trade_status.equals("TRADE_FINISHED")) {
				
			} else if (trade_status.equals("TRADE_SUCCESS")) {
				ShopOrderPay shopOrderPay = shopOrderService.findShopOrderPayByPayNum(out_trade_no);
				if(shopOrderPay == null){
					return "fail";
				}
				ShopOrder shopOrder = shopOrderService.findShopOrderById(shopOrderPay.getOrderId());
				
				if (shopOrder.getOrderStatus() == 4) {
					
				} else {
					data.put("attach", shopOrderPay.getOrderId());
					shopOrderService.updateOrderAndPayStatus(data, 2);
					
					try {
						String template = "paymentTemplate";
						List<String> email = shopOrderService
								.mailRecipient(shopOrder.getCompanyId());
						Map<String, Object> model = new HashMap<String, Object>();
						model.put("storeName", shopOrder.getShopName());
						model.put("orderNum", shopOrder.getOrderNum());
						model.put("url", Constant.WEB_MANAGER_URL);
						model.put("year",
								DateUtil.formatDateTime(shopOrder.getCreateTime())
										.substring(0, 4));
						model.put("month",
								DateUtil.formatDateTime(shopOrder.getCreateTime())
										.substring(5, 7));
						model.put("day",
								DateUtil.formatDateTime(shopOrder.getCreateTime())
										.substring(8, 10));
						model.put("time",
								DateUtil.formatDateTime(shopOrder.getCreateTime())
										.substring(11, 19));
						sendEmailService.sendEmailFromTemplate(template, email,
								model);
					} catch (Exception e) {
						return "fail";
					}
				}
			}
			
			return "success";

		} else {
			
			return "fail";
		}

	}

	// 旺POS推送付款结果
	@RequestMapping(value = "payment/wposPush", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String shop_order_payment_push_wpos(HttpServletRequest request)
			throws Exception {

		HashMap<String, Object> data = new HashMap<String, Object>();

		Enumeration<?> pNames = request.getParameterNames();
		while (pNames.hasMoreElements()) {
			String name = (String) pNames.nextElement();
			String value = URLDecoder.decode(request.getParameter(name),
					"UTF-8");
			data.put(name, value);
		}

		String id = request.getParameter("attach");

		ShopOrder shopOrder = shopOrderService.findShopOrderById(Integer
				.parseInt(id));
		try {
			Integer.parseInt(id);
		} catch (Exception e) {
			return Response.error(MessageCode.ORDER_ID_WRONG);
		}

		if (shopOrder.getOrderStatus() == 4) {
			HashMap<String, Object> repeat = new HashMap<String, Object>();
			repeat.put("errCode", "0");
			repeat.put("errMsg", "支付成功");
			return Response.success(repeat);
		} else {
			shopOrderService.updateOrderAndPayStatus(data, 1);
			HashMap<String, Object> result = new HashMap<String, Object>();
			result.put("errCode", "0");
			result.put("errMsg", "支付成功");

			try {
				String template = "paymentTemplate";
				List<String> email = shopOrderService.mailRecipient(shopOrder
						.getCompanyId());
				Map<String, Object> model = new HashMap<String, Object>();
				model.put("storeName", shopOrder.getShopName());
				model.put("orderNum", shopOrder.getOrderNum());
				model.put("url", Constant.WEB_MANAGER_URL);
				model.put("year",
						DateUtil.formatDateTime(shopOrder.getCreateTime())
								.substring(0, 4));
				model.put("month",
						DateUtil.formatDateTime(shopOrder.getCreateTime())
								.substring(5, 7));
				model.put("day",
						DateUtil.formatDateTime(shopOrder.getCreateTime())
								.substring(8, 10));
				model.put("time",
						DateUtil.formatDateTime(shopOrder.getCreateTime())
								.substring(11, 19));
				sendEmailService.sendEmailFromTemplate(template, email, model);
			} catch (Exception e) {
				return Response.success("付款成功，邮件发送失败!");
			}

			return Response.success(result);
		}
	}

	// app端确认收货接口
	@RequestMapping(value = "receive", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	@Authentication
	public String shop_order_receive(HttpServletRequest request)
			throws EmptyTokenException, IllegalTokenException {

		StoreAppAccount storeAppAccount = this.getStoreAppAccount(request);
		if (storeAppAccount == null) {
			return Response.error(MessageCode.ERROR_NO_LOGIN, "未登录");
		}

		String id = request.getParameter("id");

		try {
			Integer.parseInt(id);
		} catch (Exception e) {
			return Response.error(MessageCode.ORDER_ID_WRONG);
		}

		ShopOrder shopOrder = shopOrderService.findShopOrderById(Integer
				.parseInt(id));
		if (shopOrder == null) {
			return Response.error(MessageCode.ORDER_ID_WRONG);
		} else if (shopOrder.getOrderStatus() != 6) {
			return Response.error(MessageCode.REQUEST_ERROR);
		} else {
			shopOrder.setId(Integer.parseInt(id));
			shopOrder.setOrderStatus(7);
			shopOrderService.receiveShopOrder(shopOrder);

			try {
				String template = "receiveTemplate";
				String now = DateUtil.formatDateTime(new Date());
				List<String> email = shopOrderService.mailRecipient(shopOrder
						.getCompanyId());
				Map<String, Object> model = new HashMap<String, Object>();
				model.put("storeName", shopOrder.getShopName());
				model.put("orderNum", shopOrder.getOrderNum());
				model.put("year",
						DateUtil.formatDateTime(shopOrder.getCreateTime())
								.substring(0, 4));
				model.put("month",
						DateUtil.formatDateTime(shopOrder.getCreateTime())
								.substring(5, 7));
				model.put("day",
						DateUtil.formatDateTime(shopOrder.getCreateTime())
								.substring(8, 10));
				model.put("time",
						DateUtil.formatDateTime(shopOrder.getCreateTime())
								.substring(11, 19));
				model.put("yearNow", now.substring(0, 4));
				model.put("monthNow", now.substring(5, 7));
				model.put("dayNow", now.substring(8, 10));
				model.put("timeNow", now.substring(11, 19));
				sendEmailService.sendEmailFromTemplate(template, email, model);
			} catch (Exception e) {
				return Response.success("订货单收货完成，邮件发送失败!");
			}

		}
		return Response.success("订货单收货完成!");
	}
	
		/**
		 * @description 获取订单收货地址详情
		 * @version 1.0
		 * @author 李梦龙 
		 * @date 2016年5月16日 上午10:44:05
		 * @param request
		 * @return
		 * @return String
		 * @throws
		 */
		@RequestMapping(value = "orderAddress", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
		@ResponseBody
		@Authentication
		public String shop_order_address(HttpServletRequest request){
			Integer orderId = NumberUtils.toInt(request.getParameter("id"));
			if(orderId <= 0){
				return  Response.error(MessageCode.PARAMETER_WRONG);
			}
			//查询数据库获取收货地址
			Address address = shopOrderService.getOrderAddress(orderId);
			return null;
		}

}
